<template>
  <div class="container">
    <el-dialog center destroy-on-close :model-value="show" :title="translateTitle('Dams.HSM.预览')" width="80%" @close="closePreview">
      <div>
        <vxe-grid v-bind="gridOptions" ref="vxeTable">
          <template #tableHeader="{ column }">
            <span>
              {{ column.title }}
              <el-dropdown trigger="click" @command="handleCommand($event, column)">
                <vui-icon class="filter" icon="filter-2-line" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="number">{{ translateTitle('Dams.HSM.条目数汇总') }}</el-dropdown-item>
                    <el-dropdown-item command="sum">{{ translateTitle('Dams.HSM.数量汇总') }}</el-dropdown-item>
                    <el-dropdown-item>{{ translateTitle('Dams.HSM.无') }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </span>
          </template>
          <template #tableFooter="{ items, _columnIndex }">
            <span>{{ items[_columnIndex] }}</span>
          </template>
        </vxe-grid>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="showTime">{{ translateTitle('Dams.HSM.定时发送') }}</el-button>
          <el-button type="primary" @click="sendNow">{{ translateTitle('Dams.HSM.立即发送') }}</el-button>
        </span>
      </template>
    </el-dialog>
    <timeDialog v-model:show="timeShow" />
  </div>
</template>

<script>
  import { translateTitle } from '@/utils/i18n'

  import timeDialog from './timeDialog'
  import { getList } from '@/project/dams/api/home'
  import { getStorage, removeStorage } from '@/utils/tools'
  import { GFCD } from '@/utils/utils'
  export default {
    name: 'PreviewDialog',
    components: { timeDialog },
    props: {
      show: {
        type: Boolean,
        default: false,
      },
      treeData: {
        type: Array,
        default: () => {},
      },
    },
    emits: ['update:show'],
    data() {
      return {
        configSetting: GFCD('hsm'),
        timeShow: false,
        selectTime: '',
        treeInfo: this.treeData,
        excelData: getStorage('excelData'),
        // 表格的配置数据
        tableConfig: getStorage('tableConfig'),
        result: {
          header: [],
          details: [],
          submit_type: {
            type: 'now', //now|delay
            date: '',
          },
        },
        calcMap: {},
        gridOptions: {
          showOverflow: true,
          height: 550,
          border: true,
          stripe: true,
          showFooter: true,
          align: 'center',
          columns: [],
          data: [],
          footerMethod: ({ columns, data }) => {
            let keys = Object.keys(this.calcMap)
            return [
              columns.map((column, columnIndex) => {
                if (columnIndex === 0) {
                  return '合计'
                }
                let isIncludes = keys.includes(String(column.field))

                if (isIncludes && this.calcMap[column.field] === 'number') {
                  let count = 0
                  data.forEach(() => {
                    count++
                  })
                  return `${translateTitle('Dams.HSM.条目数')}:'` + count
                } else if (isIncludes && this.calcMap[column.field] === 'sum') {
                  let count = 0
                  data.forEach((item) => {
                    count += Number(item[column.field])
                  })
                  return `${translateTitle('Dams.HSM.数量')}:` + count
                }
                return ''
              }),
            ]
          },
        },
      }
    },
    created() {},
    mounted() {
      this.addHandleConfig(this.treeInfo)
      this.gridOptions.columns = this.treeInfo
      this.gridOptions.data = this.excelData.body
      let tree = JSON.parse(JSON.stringify(this.treeInfo))
      let body = JSON.parse(JSON.stringify(this.excelData.body))
      // 将树状信息平铺为一维数组
      this.formatTree(tree)
      this.result.header.forEach((item) => {
        delete item.children
        delete item.childNum
        item.checked = item.checked ? 'Y' : 'N'
      })
      this.formatBody(body)
    },
    methods: {
      translateTitle,
      sendNow() {
        this.result.submit_type = {
          type: 'now',
          date: '',
          month: this.tableConfig.month,
          salary_type: this.tableConfig.salaryType,
        }
        this.sendData()
      },
      async sendData() {
        let method = 'hsm.excel.salarysubmit'
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify(this.result),
        })
        if (res.code === '00000') {
          this.$message({
            type: 'success',
            message: translateTitle('Dams.HSM.保存成功'),
          })
          let timer = setTimeout(() => {
            clearTimeout(timer)
            this.$message.closeAll()
            this.resetAllInfo()
            this.$router.go(0)
          }, 1500)
          return
        }
        this.$message({
          type: 'error',
          message: res.msg,
        })
      },
      // 成功后清除缓存
      resetAllInfo() {
        removeStorage('tableConfig')
        removeStorage('excelData')
        removeStorage('treeInfo')
      },
      // 当是重新上传时,替换id和pid信息
      replaceIdInfo() {},
      // 找到树结构的最底层树枝,并给该节点添加操作按钮
      addHandleConfig(tree) {
        tree.forEach((item) => {
          if (item.children && item.children.length) {
            this.addHandleConfig(item.children)
          } else {
            item.slots = {
              header: 'tableHeader',
              footer: 'tableFooter',
            }
          }
        })
      },
      // 设置统计状态
      handleCommand(com, column) {
        this.calcMap[column.field] = com
        this.$refs.vxeTable.updateData()
      },
      closePreview() {
        this.$emit('update:show', false)
        this.timeShow = false
      },
      showTime() {
        this.timeShow = true
      },
      findValue(arr, key) {
        let headerMap = this.tableConfig.headerMap
        return arr[headerMap[key]]
      },
      // 生成黑名单,黑名单内的数据不加入this.result.details
      getBlackList() {
        let list = ['user_name', 'user_no', 'phone']
        let headerMap = this.tableConfig.headerMap
        let arr = []
        list.forEach((item) => {
          arr.push(headerMap[item])
        })
        return arr
      },
      findId(key) {
        let header = this.result.header,
          headerMap = this.tableConfig.headerMap
        return header.filter((i) => i.field === headerMap[key])[0]
      },
      findTitle(field) {
        if (!field) {
          return false
        }
        let titleMap = {
          actual: translateTitle('Dams.HSM.实发薪资'),
          phone: translateTitle('Dams.HSM.手机号'),
          shouldBe: translateTitle('Dams.HSM.应发薪资'),
          standard: translateTitle('Dams.HSM.岗位标准工资'),
          user_name: translateTitle('Dams.HSM.姓名'),
          user_no: translateTitle('Dams.HSM.工号'),
        }
        let headerMap = JSON.parse(JSON.stringify(this.tableConfig.headerMap))
        for (let k in headerMap) {
          let value = headerMap[k] //将原来的value赋值给一个变量
          headerMap[value] = k // 为headerMap赋新key，不能直接使用headerMap = {headerMap[k] : k},会报语法错误
          delete headerMap[k] // 删除原来的属性
        }
        return titleMap[headerMap[field]]
      },
      formatBody(body) {
        this.result.details = []
        let detailSort = 0
        let salaryType = this.tableConfig.salaryType,
          month = this.tableConfig.month
        let header = this.result.header
        let blackList = this.getBlackList()
        body.forEach((item) => {
          let keys = Object.keys(item)
          keys.forEach((itemIn) => {
            for (let i = 0; i < header.length; i++) {
              let ele = header[i]
              if (ele.field == itemIn && !blackList.includes(ele.field)) {
                this.result.details.push({
                  user_name: this.findValue(item, 'user_name'),
                  user_no: this.findValue(item, 'user_no'),
                  phone: this.findValue(item, 'phone'),
                  item: ele.title,
                  note_value: item[itemIn],
                  sort: detailSort,
                  salary_type: salaryType,
                  pid: ele.pid,
                  month: month,
                  id: ele.id,
                })
                detailSort++
                break
              }
            }
          })
        })
      },
      // 将树状表头信息扁平化
      formatTree(tree) {
        tree.forEach((item, index) => {
          item.sort = index
          item.month = this.tableConfig.month
          item.salary_type = this.tableConfig.salaryType
          item.pid || item.pid == 0 ? '' : (item.pid = '')
          item.title = item.title.replace(/\s+/g, '')
          let title = this.findTitle(item.field)
          if (title) {
            item.title = title
          }
          this.result.header.push(item)
          if (item.children || item.children.length) {
            this.formatTree(item.children)
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped></style>
